package org.zhxy.core.system.service;

import com.baidu.aip.util.Base64Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.zhxy.common.response.FaceLoginResult;
import org.zhxy.common.response.QRCode;
import org.zhxy.common.utils.BaiduAiUtil;
import org.zhxy.common.utils.IdWorker;
import org.zhxy.common.utils.QRCodeUtil;
import org.zhxy.core.system.mapper.UserMapper;
import org.zhxy.entity.system.User;

import java.util.concurrent.TimeUnit;

@Service
public class FaceLoginService {

    @Value("${qr.url}")
    private String url;

    @Autowired
    private BaiduAiUtil baiduAiUtil;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private QRCodeUtil qrCodeUtil;

    @Autowired
    private UserMapper userMapper;

    public QRCode getQRCode() throws Exception {
        String code = idWorker.nextId();
        String content = url + "?code=" + code;
        //String file = qrCodeUtil.crateQRCode(content);
        FaceLoginResult result = new FaceLoginResult("-1");
        redisTemplate.boundValueOps(getCacheKey(code)).set(result,10, TimeUnit.MINUTES);

        return new QRCode(code);
    }

    public FaceLoginResult checkQRCode(String code) {
        String key = getCacheKey(code);
        return (FaceLoginResult) redisTemplate.opsForValue().get(key);
    }

    public String loginByFace(String code, MultipartFile attachment) throws Exception {
        String image = Base64Util.encode(attachment.getBytes());
        String userId = baiduAiUtil.faceSearch(image);
        String token = null;
        FaceLoginResult result = new FaceLoginResult("0");
        if(userId != null){
            User user = userMapper.selectById(userId);
            UsernamePasswordToken upToken = new UsernamePasswordToken(user.getUsername(),user.getPassword());
            Subject subject = SecurityUtils.getSubject();
            subject.login(upToken);
            token = (String)subject.getSession().getId();
            result = new FaceLoginResult("1",token,userId);
        }

        redisTemplate.boundValueOps(getCacheKey(code)).set(result,10,TimeUnit.MINUTES);
        return token;
    }

    private String getCacheKey(String code) {
        return "qrcode_" + code;
    }
}

